package com.dure.commonlib.util;

import com.socks.library.KLog;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by leix on 8/16/16.
 */
public class StreamUtil {

    public static String inputStream2String(InputStream in) {

        StringBuffer out = new StringBuffer();
        // 以byte 数组来读取数据时会有乱码的情况，
//        byte[] b = new byte[1024];
        char[] c = new char[1024];
        int n;
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(in, "utf-8");
//            BufferedInputStream bufferedInputStream = new BufferedInputStream(in,"");
//            inputStreamReader.read(c, )
            while ((n = inputStreamReader.read(c)) != -1) {
                out.append(new String(c, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toString();
    }

    public static byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }
}
